package com.mmall.util;

import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.codehaus.jackson.type.TypeReference;

/**
 * 实体类 和 json字符串之间的转换
 * Created by pc on 2019/3/23.
 */
@Slf4j
public class JsonMapper {
    private static ObjectMapper objectMapper = new ObjectMapper();

    //初始化参数 空参数不转化
    static{
        // config
        objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);
        objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
        objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
    }

    public static <T>String obj2String(T src){
        if(src == null){
            return null;
        }
        try {
            return src instanceof String ? (String)src : objectMapper.writeValueAsString(src);
        }catch (Exception e){
            log.error("parse objece to  string exception T:{},error:{}",src,e);
            return null;
        }
    }

    public static <T> T string2Obj(String src, TypeReference<T> reference){
        if(src == null || reference == null){
            return null;
        }
        try {
            return (T)(reference.getType().equals(String.class) ? src : objectMapper.readValue(src,reference));
        }catch (Exception e){
            log.warn("parse string to object exception String:{},TypeReference<T>:{},error:{}",src,reference.getType(),e);
            return null;
        }
    }
}
